package com.hqd.ch03.v10.reader.xml.doc.support;

import com.hqd.ch03.v10.io.Resource;
import com.hqd.ch03.v10.reader.xml.doc.DocumentLoader;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class DefaultDocumentLoader implements DocumentLoader {
    protected static final String SCHEMA_LANGUAGE_ATTRIBUTE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    protected static final String XSD_SCHEMA_LANGUAGE = "http://www.w3.org/2001/XMLSchema";

    protected InputSource getInputSource(Resource resource) throws Exception {
        return new InputSource(resource.getInputStream());
    }

    @Override
    public Document loadDocument(Resource resource, EntityResolver resolver, ErrorHandler errorHandler) {
        try {
            InputSource inputSource = getInputSource(resource);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            /**
             * 设置为true，获取namespaceURI
             * dtd需要设置成false
             */
            factory.setNamespaceAware(true);
            /**
             * 开启验证模式
             */
            factory.setValidating(true);
            /**
             * xsd需要设置，dtd不需要
             */
            factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            /**
             * 设置验证失败处理器
             */
            docBuilder.setErrorHandler(errorHandler);
            /**
             * 指定xml验证器
             */
            docBuilder.setEntityResolver(resolver);
            return docBuilder.parse(inputSource);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
